In [1]:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# Define the path to the text file
file_path = '../../Seisbench/OK_Event_Lat_Lon_Time_Depth_Mag.txt'
# Read the text file into a pandas DataFrame
df = pd.read_csv(file_path, sep=' ', header=None, names=['latitude', 'longitude', 'time', 'depth', 'magnitude'])
# Convert the 'time' column to a pandas datetime object
df['time'] = pd.to_datetime(df['time'])
# Group by month and count the number of events in each month
df['year_month'] = df['time'].dt.to_period('M') # Extract year and month as a Period object
# Define magnitude bins (you can customize this based on your data)
bins = [0, 2, 3, 4, 5, 6] # Magnitude ranges (e.g., 0-2, 2-3, etc.)
labels = ['0-2', '2-3', '3-4', '4-5', '5-6'] # Labels for magnitude ranges
# Assign each event to a magnitude bin
df['magnitude_bin'] = pd.cut(df['magnitude'], bins=bins, labels=labels, right=False)
# Create a pivot table to count the number of events per month and per magnitude bin
monthly_events = df.pivot_table(index='year_month', columns='magnitude_bin', aggfunc='size', fill_value=0)
# Convert 'year_month' to datetime for plotting
monthly_events.index = monthly_events.index.to_timestamp()
# Prepare data for stackplot (each row represents a magnitude category)
magnitudes = monthly_events[labels] # Extracting the event counts for each magnitude bin
# Plot the stackplot
plt.figure(figsize=(12, 8))
plt.stackplot(monthly_events.index, magnitudes.T, labels=labels, colors=['#c6dbef', '#6baed6', '#2171b5', '#08306b', '#fdae6b'], alpha=0.8)
# Format x-axis to show every 6 months instead of every month
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=6)) # Show every 6th month
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
# Add labels, title, and grid for better appearance
plt.xlabel('Month', fontsize=14, labelpad=10)
plt.ylabel('Number of Events', fontsize=14, labelpad=10)
plt.title('Monthly Seismic Event Counts by Magnitude', fontsize=16, pad=20)
# Add legend
plt.legend(title="Magnitude Range", loc="upper left", fontsize=12)
# Customize x and y ticks
plt.xticks(rotation=45, fontsize=12)
plt.yticks(fontsize=12)
# Adding grid for better readability
plt.grid(True, which='both', linestyle='--', linewidth=0.7, alpha=0.7)
# Remove top and right spines for a cleaner look
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
# Tight layout to avoid clipping
plt.tight_layout()
# Show plot
plt.show()
/var/folders/sd/gqkj0t9n16n8_qtbhd_wlhp80000gq/T/ipykernel_85600/3037062059.py:15: UserWarning: Converting to PeriodArray/Index representation will drop timezone information. df['year_month'] = df['time'].dt.to_period('M') # Extract year and month as a Period object /var/folders/sd/gqkj0t9n16n8_qtbhd_wlhp80000gq/T/ipykernel_85600/3037062059.py:25: FutureWarning: The default value of observed=False is deprecated and will change to observed=True in a future version of pandas. Specify observed=False to silence this warning and retain the current behavior monthly_events = df.pivot_table(index='year_month', columns='magnitude_bin', aggfunc='size', fill_value=0)
In [2]:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# Define the path to the text file
file_path = '../../Seisbench/OK_Event_Lat_Lon_Time_Depth_Mag.txt'
# Read the text file into a pandas DataFrame
df = pd.read_csv(file_path, sep=' ', header=None, names=['latitude', 'longitude', 'time', 'depth', 'magnitude'])
# Convert the 'time' column to a pandas datetime object
df['time'] = pd.to_datetime(df['time'])
# Group by month and count the number of events in each month
df['year_month'] = df['time'].dt.to_period('M') # Extract year and month as a Period object
# Define magnitude bins (you can customize this based on your data)
bins = [0, 2, 3, 4, 5, 6] # Magnitude ranges (e.g., 0-2, 2-3, etc.)
labels = ['0-2', '2-3', '3-4', '4-5', '5-6'] # Labels for magnitude ranges
# Assign each event to a magnitude bin
df['magnitude_bin'] = pd.cut(df['magnitude'], bins=bins, labels=labels, right=False)
# Create a pivot table to count the number of events per month and per magnitude bin
monthly_events = df.pivot_table(index='year_month', columns='magnitude_bin', aggfunc='size', fill_value=0)
# Convert 'year_month' to datetime for plotting
monthly_events.index = monthly_events.index.to_timestamp()
# Prepare data for stackplot (each row represents a magnitude category)
magnitudes = monthly_events[labels].T # Extracting the event counts for each magnitude bin
# Plot the stackplot with a symmetric baseline
fig, ax = plt.subplots(figsize=(12, 8))
ax.stackplot(monthly_events.index, magnitudes, labels=labels,
colors=['#c6dbef', '#6baed6', '#2171b5', '#08306b', '#fdae6b'],
alpha=0.8, baseline="sym")
# Add a horizontal line at y=0 for reference
ax.axhline(0, color="black", linestyle="--")
# Format x-axis to show every 6 months instead of every month
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=6)) # Show every 6th month
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
# Add labels, title, and grid for better appearance
ax.set_xlabel('Month', fontsize=14, labelpad=10)
ax.set_ylabel('Number of Events', fontsize=14, labelpad=10)
ax.set_title('Symmetric Monthly Seismic Event Counts by Magnitude', fontsize=16, pad=20)
# Add legend
ax.legend(title="Magnitude Range", loc="upper left", fontsize=12)
# Customize x and y ticks
plt.xticks(rotation=45, fontsize=12)
plt.yticks(fontsize=12)
# Adding grid for better readability
plt.grid(True, which='both', linestyle='--', linewidth=0.7, alpha=0.7)
# Remove top and right spines for a cleaner look
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# Tight layout to avoid clipping
plt.tight_layout()
# Show plot
plt.show()
/var/folders/sd/gqkj0t9n16n8_qtbhd_wlhp80000gq/T/ipykernel_85600/3672238902.py:15: UserWarning: Converting to PeriodArray/Index representation will drop timezone information. df['year_month'] = df['time'].dt.to_period('M') # Extract year and month as a Period object /var/folders/sd/gqkj0t9n16n8_qtbhd_wlhp80000gq/T/ipykernel_85600/3672238902.py:25: FutureWarning: The default value of observed=False is deprecated and will change to observed=True in a future version of pandas. Specify observed=False to silence this warning and retain the current behavior monthly_events = df.pivot_table(index='year_month', columns='magnitude_bin', aggfunc='size', fill_value=0)
In [ ]: